var http=require("http");
var path=require("path");
var fs=require("fs");
var server=http.createServer(function (req,res) {
    var resA=res;
    var htmlData="";
    var imgPath;
    http.get("http://www.imooc.com/",function (res) {
        res.on("data",function (data) {
            htmlData+=data;
        });
        res.on("end",function () {
             resA.statusCode=200;
             resA.setHeader("Content-Type","text/html");
             resA.end(htmlData);
            var imgPathReg=/src="(.*?[\.jpg|\.png|\.gif])"/img;
            while (imgPath=imgPathReg.exec(htmlData)){

                getImgPath(imgPath[1]);
            }
        })
    })

}).listen(2000,function () {
    console.log("服务已启动！");
});

function getImgPath(url) {
    var fObj=path.parse(url);
    /*得到图片名称*/
    var imgName=fObj.base;
    /*得到图片路径*/
    if(url.substr(0,4)=="http"){
        url=url;
    }else{
        url="http://www.imooc.com"+url;
    }

    /*写入数据流*/
    var writeImg=fs.createWriteStream("./files/"+imgName);

    http.get(url,function (res) {
          res.pipe(writeImg);
          console.log(imgName+"下载完成！");
    })
}